package com.winai.launcher.view.set;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.thanosfisherman.wifiutils.WifiUtils;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionErrorCode;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionSuccessListener;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.WifiItemBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.manager.WifiAutoConnectManager;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.override.dialog_global.GlobalDialog;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/11/19 0019
 * 说明：密码连接wifi
 */
public class SetWifiLinkActivity extends BaseActivity {
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.tv_link)
    TextView tvLink;
    @BindView(R.id.tv_connectWifi)
    TextView tvConnectWifi;
    @BindView(R.id.et_psw)
    EditText etPsw;
    @BindView(R.id.iv_eye)
    ImageView ivEye;
    @BindView(R.id.tv_errorTip)
    TextView tvErrorTip;
    @BindView(R.id.iv_clear)
    ImageView ivClear;

    private Context mContext = this;
    private boolean isHideFirst = true;// 输入框密码是否是隐藏的，默认为true

    private WifiItemBean mWifiItemBean;
    private AlphaAnimation showAnim;
    private Animation loadingAnimation;

    private WifiManager mWifiManager;
    private WifiAutoConnectManager wifiAutoConnectManager;
    private GlobalDialog.Builder tipDialog;//提示弹窗

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_wifi_link);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initView();
    }

    private void initObject() {
        String titleName = getIntent().getStringExtra("titleName");
        mWifiItemBean = getIntent().getParcelableExtra("WifiItemBean");
        strTitle.setText(titleName);
        if (mWifiItemBean != null) {
            tvConnectWifi.setText(mWifiItemBean.getWifiName());
        }

        showAnim = new AlphaAnimation(0, 1);
        showAnim.setDuration(500);

        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());

        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiAutoConnectManager = WifiAutoConnectManager.newInstance(mWifiManager);

        tipDialog = new GlobalDialog.Builder(mContext)
                .setTitle("网络连接失败")
                .setContent("请检查您的网络和密码，重新尝试连接")
                .setCancelText("好的")
                .setCancelAble(false)
                .setCancelGradient(true)
                .setOnCancelClickListener((mGlobalDialog, v) -> {
                    // 取消保存，忽略网络，忽略WiFi，忘记网络
                    wifiAutoConnectManager.removeWifiBySsid(mWifiItemBean.getWifiName());
                    GlobalPublisher.Notify(GlobalPublisher.CHANGE_WIFI, 0);
                    etPsw.setText("");
                    //打开键盘
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        public void run() {
                            InputMethodManager inputManager =
                                    (InputMethodManager) etPsw.getContext().getSystemService(
                                            Context.INPUT_METHOD_SERVICE);
                            inputManager.showSoftInput(etPsw, 0);
                        }
                    }, 500);
                });
    }

    private void toggleLinking(boolean linking) {
        if (linking) {
            ivRefresh.setVisibility(View.VISIBLE);
            tvLink.setVisibility(View.GONE);
            showProgressBar();
            // 收起键盘，psw不可点击
            InputMethodManager manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
            if (manager != null)
                manager.hideSoftInputFromWindow(etPsw.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            etPsw.setEnabled(false);
            ivClear.setClickable(false);
        } else {
            ivRefresh.setVisibility(View.GONE);
            tvLink.setVisibility(View.VISIBLE);
            hidingProgressBar();
            // 打开键盘，psw可点击
            etPsw.setEnabled(true);
            ivClear.setClickable(true);
            //打开键盘
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    InputMethodManager inputManager =
                            (InputMethodManager) etPsw.getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(etPsw, 0);
                }
            }, 500);
        }
    }

    public void showProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ivRefresh.startAnimation(loadingAnimation);
            }
        });
    }

    public void hidingProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ivRefresh.clearAnimation();
            }
        });
    }

    private void initView() {
        toggleBtnDisableOrEnable(true);
    }

    private void toggleBtnDisableOrEnable(boolean enable) {
        if (enable) {
            tvLink.setOnClickListener(v -> {
                // 连接wifi
                WifiUtils.withContext(mContext)
                        .connectWith(mWifiItemBean.getWifiName(), mWifiItemBean.getBSSID(), etPsw.getText().toString())
                        .setTimeout(15000)
                        .onConnectionResult(new ConnectionSuccessListener() {
                            @Override
                            public void success() {
                                linkSuccess();
                            }

                            @Override
                            public void failed(@NonNull ConnectionErrorCode errorCode) {
//                                if (NetworkManager.getInstance(mContext).getConnectedWifi() != null) {
//                                    LogUtils.d("拦截掉联网失败操作");
//                                    linkSuccess();
//                                } else {
                                linkFailed(errorCode);
//                                }
                            }
                        })
                        .start();
                toggleLinking(true);
            });
        } else {
            tvLink.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tvErrorTip.setVisibility(View.VISIBLE);
                    tvErrorTip.startAnimation(showAnim);
                }
            });
        }
        tvErrorTip.setVisibility(enable ? View.GONE : View.VISIBLE);
        tvLink.setBackground(getResources().getDrawable(enable ? R.drawable.selector_btn_green_100dp : R.drawable.bg_btn_green_100dp_dark));
    }

    private void linkFailed(@NonNull ConnectionErrorCode errorCode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                toggleLinking(false);
                if (errorCode == ConnectionErrorCode.TIMEOUT_OCCURRED) {
                    tipDialog.setContent("连接超时，重新尝试连接");
                } else if (errorCode == ConnectionErrorCode.DID_NOT_FIND_NETWORK_BY_SCANNING) {
                    tipDialog.setContent("该网络不在范围内，重新尝试连接");
                } else if (errorCode == ConnectionErrorCode.AUTHENTICATION_ERROR_OCCURRED) {
                    tipDialog.setContent("身份验证错误，重新尝试连接");
                } else {
                    tipDialog.setContent("请检查您的网络和密码，重新尝试连接");
                }
                tipDialog.show();
            }
        });
    }

    private void linkSuccess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                toggleLinking(false);
                ToastKs.show(mContext, "连接成功");
                mWifiItemBean.setWifiPsw(etPsw.getText().toString());
                DB_Common dbCommon = new DB_Common(mContext);
                String isFirst = dbCommon.get("isFirstOpenApp");
                if (TextUtils.isEmpty(isFirst)) {
                    //第一次打开设备
                    GlobalPublisher.Notify(GlobalPublisher.LINK_CONFIG_WIFI, mWifiItemBean);
                } else {
                    GlobalPublisher.Notify(GlobalPublisher.LINK_WIFI, mWifiItemBean);
                }
                Intent intent = new Intent();
                intent.putExtra("finishAct", true);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.iv_eye, R.id.iv_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.iv_clear:
                etPsw.setText("");
                break;
            case R.id.iv_eye:
                if (isHideFirst) {
                    ivEye.setImageResource(R.mipmap.icon_eye_open);
                    //密文
                    HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                    etPsw.setTransformationMethod(method1);
                    isHideFirst = false;
                } else {
                    ivEye.setImageResource(R.mipmap.icon_eye_close);
                    //明文
                    TransformationMethod method = PasswordTransformationMethod.getInstance();
                    etPsw.setTransformationMethod(method);
                    isHideFirst = true;
                }
                // 光标的位置
                int index = etPsw.getText().toString().length();
                etPsw.setSelection(index);
                break;
        }
    }
}
